package org.ldx.lotterysystem.controller;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.ldx.lotterysystem.common.utils.JacksonUtil;
import org.ldx.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import org.ldx.lotterysystem.common.exception.ControllerException;
import org.ldx.lotterysystem.common.pojo.CommonResult;
import org.ldx.lotterysystem.controller.param.MessageLoginParam;
import org.ldx.lotterysystem.controller.param.UserPasswordLoginParam;
import org.ldx.lotterysystem.controller.result.UserInfoListResult;
import org.ldx.lotterysystem.controller.result.UserLoginResult;
import org.ldx.lotterysystem.controller.param.UserRegisterParam;
import org.ldx.lotterysystem.controller.result.UserRegisterResult;
import org.ldx.lotterysystem.service.UserService;
import org.ldx.lotterysystem.service.dto.UserDto;
import org.ldx.lotterysystem.service.dto.UserLoginDto;
import org.ldx.lotterysystem.service.dto.UserRegisterDTO;
import org.ldx.lotterysystem.service.enums.UserIdentityEnum;
import org.ldx.lotterysystem.service.impl.VerificationCodeServiceImpl;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private VerificationCodeServiceImpl verificationCodeService;
   // private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @PostMapping("/register")
    public CommonResult<UserRegisterResult> register(@Valid @RequestBody UserRegisterParam param){
        //验证log的区别
        //logger.info("userRegister UserRegisterParam{}", JacksonUtil.writeValueAsString(param));
//        logger.info("2---userRegister UserRegisterParam{}", param);
        log.info("userRegister UserRegisterParam{}", JacksonUtil.writeValueAsString(param));

        return CommonResult.success(converToUserRegisterResult(userService.register(param)));
    }
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(String phoneNumber){
        log.info("sendVerificationCode email{}",phoneNumber);
        verificationCodeService.sendVerificationCode(phoneNumber);
        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 密码登录
     * @param param
     * @return
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(
            @RequestBody @Validated UserPasswordLoginParam param){
        log.info("userPasswordLogin UserPasswordLoginParam{}",
                JacksonUtil.writeValueAsString(param));
        UserLoginDto userLoginDto = userService.login(param);
        System.out.println("要开始转换了：对象："+userLoginDto.getIdentity()+userLoginDto.getToken());
        return CommonResult.success(converToUserLoginResult(userLoginDto));
    }

    /**
     * 验证码登录
     * @param param
     * @return
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> messageLogin(
            @RequestBody @Validated MessageLoginParam param){
        log.info("messageLogin MessageLoginParam{}",
                JacksonUtil.writeValueAsString(param));
        UserLoginDto userLoginDto = userService.login(param);
        return CommonResult.success(converToUserLoginResult(userLoginDto));
    }

    /**
     * 获取人员列表
     * @param userLoginDto
     * @return
     */
    @RequestMapping("/base-user/find-list")
    public CommonResult<List<UserInfoListResult>> findUserInfoList(String identity){
        log.info("findUserInfoList identity:{}",identity);
        List<UserDto> userDtoList = userService.findUserInfoList(UserIdentityEnum.forName(identity));
        return CommonResult.success(converToUserInfoListResult(userDtoList));
    }

    private List<UserInfoListResult> converToUserInfoListResult(List<UserDto> userDtoList) {
        if(null == userDtoList){
            return Arrays.asList();
        }
        return userDtoList.stream()
                .map(userDto -> {
                    UserInfoListResult result = new UserInfoListResult();
                    result.setUserName(userDto.getUserName());
                    result.setIdentity(userDto.getIdentity().getMessage());
                    result.setUserId(userDto.getUserId());
                    return result;
                }).collect(Collectors.toList());
    }

    private UserLoginResult converToUserLoginResult(UserLoginDto userLoginDto) {
        if(null == userLoginDto){//null写前面，避免空指针错误
            System.out.println("转换中");
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        UserLoginResult result = new UserLoginResult();
        result.setIdentity(userLoginDto.getIdentity().name());
        result.setToken(userLoginDto.getToken());
        return result;
    }

    private UserRegisterResult converToUserRegisterResult(UserRegisterDTO register) {
        if(null == register){//null写前面，避免空指针错误
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        UserRegisterResult result = new UserRegisterResult();
        result.setUserId(register.getUserId());

        return result;
     }
}
